/*
 * @lc app=leetcode.cn id=25 lang=javascript
 *
 * [25] K 个一组翻转链表
 */
let createNode = require('./tools/create-node');
let listNodeToArr = require('./tools/list-node-to-arr');
// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 * 执行用时：112 ms, 在所有 JavaScript 提交中击败了34.68%的用户
 * 内存消耗：40.9 MB, 在所有 JavaScript 提交中击败了74.05%的用户
 */
// var reverseKGroup = function (head, k) {
//     let pre = head;
//     let final = head;
//     for(let i = 0; i < k; i++) {
//         if(final == null) {
//             return head;
//         } else {
//             final = final.next;
//         }
//     }
//     let list =  null;
//     while(head != final) {
//         let next = head.next;
//         head.next = list;
//         list = head;
//         head = next;
//     }
//     let tail = reverseKGroup(final, k);
//     pre.next = tail;
//     return list;
// };

function reverseKGroup(head, k) {
    console.log('***********************')
    let resultNode = null;
    let tail = head;
    let nextWhileNodeHead = null;
    while(true) {
        if(head == null) return resultNode;
        let preHead = head;
        if(nextWhileNodeHead != null) {
            nextWhileNodeHead.next = head;
        }
        for(let i = 0; i < k - 1; i++) {
            if(tail == null) {
                console.log('--------------------------')
                return resultNode;
            } else {
                tail = tail.next;
            }
        }
        // nextWhileNodeHead.next = head;
        while(--k) {
            console.log('----------k start-------------');
            let temp = tail.next;
            let newHead = head.next == null ? null:head.next;
            head.next = temp;
            tail.next = head;
            head = newHead;
            console.log('----------k end-------------')
        }
        if(resultNode == null) {
            resultNode = tail;
        }
        // nextWhileNodeHead = preHead;
        // console.log('nextWhileNodeHead', nextWhileNodeHead);
        console.log(preHead)
        head = preHead.next;
        console.log('head---', JSON.stringify(head));
        tail = head;
        console.log(JSON.stringify(resultNode));
        // break;
    }

}
// @lc code=end
function run() {
    let arg = createNode.createNode([1,2,3]);
    let result = reverseKGroup(arg, 3);
    return result;
}
module.exports = run;
